﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using System.Web;
using System.Security.Principal;

/// <summary>
/// Summary description for LoginService
/// </summary>
public class LoginService
{
    private static String[] GetRolesBy(String username, String password, ref int userID)
    {
        using (DatabaseDataContext context = DataFactory.GetDataContext())
        {
            var query = from u in context.Users
                        join userInRoles in context.UserRoles
                        on
                        u.UserID equals userInRoles.Id
                        join sysRoles in context.Roles
                        on
                        userInRoles.RoleId equals sysRoles.RoleId
                        where
                        u.UserName == username
                        && u.Password == password

                        && userInRoles.Active == true
                        && sysRoles.Active == true
                        select new { u.UserID, sysRoles.RoleName };


            var resultList = query.ToList().ToArray();

            if (resultList.Length > 0)
            {
                String[] roles = new String[resultList.Length];
                for (int i = 0; i < roles.Length; i++)
                {
                    userID = resultList[i].UserID;
                    roles[i] = resultList[i].RoleName;
                }

                return roles;
            }
        }

        return null;
    }
    /// <summary>
    /// Authenticate user & password.
    /// Return null if user doesn't exist.
    /// Otherwise, retur user's cookie
    /// </summary>
    /// <param name="username"></param>
    /// <param name="password"></param>
    /// <returns></returns>
    public static HttpCookie Authenticate(String username, String password, out int userID)
    {
        HttpCookie authCookie = null;
        userID = -1;
        String[] roles = GetRolesBy(username, password, ref userID);

        if (roles != null)
        {
            String tmp = String.Empty;
            foreach (String role in roles)
            {
                tmp += role + "|";
            }
            FormsAuthenticationTicket ticket;
            //ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(30), true, tmp);


            ticket = new FormsAuthenticationTicket(1, userID.ToString(), DateTime.Now, DateTime.Now.AddHours(1), true, tmp);
            // Now encrypt the ticket.
            string encryptedTicket = FormsAuthentication.Encrypt(ticket);
            // Create a cookie and add the encrypted ticket to the
            // cookie as data.
            authCookie = new HttpCookie(FormsAuthentication.FormsCookieName,
                                        encryptedTicket);

        }

        return authCookie;
    }
    #region public static int GetUserIdBy(String userName, String userPass)
    /// <summary>
    /// Get userId by userName and Password
    /// </summary>
    /// <param name="userName"></param>
    /// <param name="userPass"></param>
    /// <returns></returns>
    public static int GetUserIdBy(String userName, String userPass)
    {
        int userId = -1;
        using (DatabaseDataContext context = DataFactory.GetDataContext())
        {
            var query = from user in context.Users
                        where
                        user.UserName == userName
                        && user.Password == userPass
                        select new { user.UserID };
            var result = query.SingleOrDefault();

            if (result != null)
                userId = result.UserID;
        }
        return userId;

    }
    #endregion

    public static void SignOut()
    {
        if (HttpContext.Current != null)
            HttpContext.Current.Session.Abandon();

        FormsAuthentication.SignOut();
    }
}